<template>
  <div class="property-panel">
    <div class="panel-header">
      <h3>属性面板</h3>
      <div class="panel-tabs">
        <div 
          class="tab-item" 
          :class="{ 'active': activeTab === 'props' }" 
          @click="activeTab = 'props'"
        >
          属性
        </div>
        <div 
          class="tab-item" 
          :class="{ 'active': activeTab === 'dataBinding' }" 
          @click="activeTab = 'dataBinding'"
        >
          数据绑定
        </div>
      </div>
    </div>
    
    <div class="panel-content">
      <!-- 未选中组件时的提示 -->
      <div v-if="!selectedComponent" class="empty-tip">
        <p>请选择一个组件以编辑其属性</p>
      </div>
      
      <!-- 选中组件时显示属性编辑表单 -->
      <template v-else>
        <!-- 属性面板 -->
        <div v-if="activeTab === 'props'">
        <!-- 组件基本信息 -->
        <div class="property-section">
          <h4 class="section-title">基本信息</h4>
          
          <div class="property-item">
            <div class="property-label">组件类型</div>
            <div class="property-value">{{ selectedComponent.type }}</div>
          </div>
          
          <div class="property-item">
            <div class="property-label">组件ID</div>
            <div class="property-value">{{ selectedComponent.id }}</div>
          </div>
        </div>
        
        <!-- 样式属性 -->
        <div class="property-section">
          <h4 class="section-title">样式属性</h4>
          
          <div class="property-item">
            <div class="property-label">宽度</div>
            <input 
              type="text" 
              class="form-input" 
              v-model="styleProps.width"
              @change="updateStyle('width', styleProps.width)"
            />
          </div>
          
          <div class="property-item">
            <div class="property-label">高度</div>
            <input 
              type="text" 
              class="form-input" 
              v-model="styleProps.height"
              @change="updateStyle('height', styleProps.height)"
            />
          </div>
          
          <div class="property-item">
            <div class="property-label">位置 X</div>
            <input 
              type="text" 
              class="form-input" 
              v-model="styleProps.left"
              @change="updateStyle('left', styleProps.left)"
            />
          </div>
          
          <div class="property-item">
            <div class="property-label">位置 Y</div>
            <input 
              type="text" 
              class="form-input" 
              v-model="styleProps.top"
              @change="updateStyle('top', styleProps.top)"
            />
          </div>
          
          <div class="property-item">
            <div class="property-label">背景颜色</div>
            <input 
              type="color" 
              class="form-input color-input" 
              v-model="styleProps.backgroundColor"
              @change="updateStyle('backgroundColor', styleProps.backgroundColor)"
            />
          </div>
        </div>
        
        <!-- 组件属性 -->
        <div class="property-section">
          <h4 class="section-title">组件属性</h4>
          
          <!-- 根据组件类型显示不同的属性编辑表单 -->
          <template v-if="selectedComponent.type === 'input'">
            <div class="property-item">
              <div class="property-label">标签文本</div>
              <input 
                type="text" 
                class="form-input" 
                v-model="componentProps.label"
                @change="updateProps('label', componentProps.label)"
              />
            </div>
            
            <div class="property-item">
              <div class="property-label">占位文本</div>
              <input 
                type="text" 
                class="form-input" 
                v-model="componentProps.placeholder"
                @change="updateProps('placeholder', componentProps.placeholder)"
              />
            </div>
          </template>
          
          <template v-else-if="selectedComponent.type === 'button'">
            <div class="property-item">
              <div class="property-label">按钮文本</div>
              <input 
                type="text" 
                class="form-input" 
                v-model="componentProps.text"
                @change="updateProps('text', componentProps.text)"
              />
            </div>
            
            <div class="property-item">
              <div class="property-label">按钮类型</div>
              <select 
                class="form-input" 
                v-model="componentProps.type"
                @change="updateProps('type', componentProps.type)"
              >
                <option value="default">默认</option>
                <option value="primary">主要</option>
                <option value="success">成功</option>
                <option value="warning">警告</option>
                <option value="danger">危险</option>
              </select>
            </div>
          </template>
          
          <template v-else-if="selectedComponent.type === 'text'">
            <div class="property-item">
              <div class="property-label">文本内容</div>
              <textarea 
                class="form-input" 
                v-model="componentProps.content"
                @change="updateProps('content', componentProps.content)"
                rows="4"
              ></textarea>
            </div>
          </template>
          
          <template v-else-if="selectedComponent.type === 'custom-js'">
            <div class="property-item">
              <div class="property-label">自定义JS代码</div>
              <textarea 
                class="form-input code-editor" 
                v-model="componentProps.code"
                @change="updateProps('code', componentProps.code)"
                rows="8"
              ></textarea>
            </div>
          </template>
          
          <!-- 其他组件类型的属性编辑表单 -->
        </div>
        
        <!-- 事件处理 -->
        <div class="property-section">
          <h4 class="section-title">事件处理</h4>
          
          <div class="property-item" v-if="['button', 'input', 'select'].includes(selectedComponent.type)">
            <div class="property-label">点击事件</div>
            <textarea 
              class="form-input code-editor" 
              v-model="events.click"
              @change="updateEvent('click', events.click)"
              rows="4"
              placeholder="输入事件处理代码..."
            ></textarea>
          </div>
          
          <div class="property-item" v-if="['input', 'select', 'checkbox', 'radio'].includes(selectedComponent.type)">
            <div class="property-label">值变化事件</div>
            <textarea 
              class="form-input code-editor" 
              v-model="events.change"
              @change="updateEvent('change', events.change)"
              rows="4"
              placeholder="输入事件处理代码..."
            ></textarea>
          </div>
        </div>
        
        <!-- JSON导出 -->
        <div class="property-section">
          <h4 class="section-title">组件JSON</h4>
          
          <div class="property-item">
            <textarea 
              class="form-input json-viewer" 
              v-model="componentJson"
              rows="8"
              readonly
            ></textarea>
          </div>
          
          <div class="property-actions">
            <button class="btn" @click="copyJson">复制JSON</button>
            <button class="btn" @click="showJsonEditor = true">编辑JSON</button>
          </div>
        </div>
        </div>
        
        <!-- 数据绑定面板 -->
        <div v-else-if="activeTab === 'dataBinding'" class="data-binding-panel">
          <div class="property-section">
            <h4 class="section-title">数据绑定</h4>
            
            <div v-if="dataItems.length === 0" class="empty-tip">
              <p>数据池为空，请先添加数据项</p>
            </div>
            
            <template v-else>
              <div class="binding-description">
                <p>选择要绑定的组件属性和数据项</p>
              </div>
              
              <!-- 绑定配置 -->
              <div class="binding-config">
                <!-- 组件属性选择 -->
                <div class="property-item">
                  <div class="property-label">组件属性</div>
                  <select class="form-input" v-model="bindingProp">
                    <option value="">请选择属性</option>
                    <optgroup label="基础属性">
                      <option v-for="(_, key) in selectedComponent.props" :key="key" :value="key">{{ key }}</option>
                    </optgroup>
                    <optgroup label="样式属性">
                      <option v-for="(_, key) in selectedComponent.style" :key="key" :value="`style:${key}`">{{ key }}</option>
                    </optgroup>
                  </select>
                </div>
                
                <!-- 数据项选择 -->
                <div class="property-item">
                  <div class="property-label">数据项</div>
                  <select class="form-input" v-model="bindingDataId">
                    <option value="">请选择数据项</option>
                    <option v-for="item in dataItems" :key="item.id" :value="item.id">{{ item.name }} ({{ item.type }})</option>
                  </select>
                </div>
                
                <!-- 绑定按钮 -->
                <div class="property-item">
                  <button class="btn primary" @click="bindData" :disabled="!bindingProp || !bindingDataId">绑定数据</button>
                </div>
              </div>
              
              <!-- 当前绑定列表 -->
              <div class="current-bindings" v-if="componentBindings.length > 0">
                <h5>当前绑定</h5>
                <div class="binding-item" v-for="(binding, index) in componentBindings" :key="index">
                  <div class="binding-info">
                    <span class="prop-name">{{ binding.propName }}</span>
                    <span class="binding-arrow">←</span>
                    <span class="data-name">{{ getDataItemName(binding.dataId) }}</span>
                  </div>
                  <button class="remove-binding-btn" @click="removeBinding(index)">×</button>
                </div>
              </div>
            </template>
          </div>
        </div>
      </template>
      
      <!-- JSON编辑对话框 -->
      <div class="json-editor-modal" v-if="showJsonEditor">
        <div class="modal-content">
          <div class="modal-header">
            <h4>编辑组件JSON</h4>
            <button class="close-btn" @click="showJsonEditor = false">×</button>
          </div>
          
          <div class="modal-body">
            <textarea 
              class="form-input json-editor" 
              v-model="editingJson"
              rows="15"
            ></textarea>
            
            <div class="error-message" v-if="jsonError">{{ jsonError }}</div>
          </div>
          
          <div class="modal-footer">
            <button class="btn" @click="showJsonEditor = false">取消</button>
            <button class="btn primary" @click="applyJsonChanges">应用</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { usePageStore, type ComponentItem } from '@/stores/page'
import { useDataPoolStore, type DataItem } from '@/stores/dataPool'

const pageStore = usePageStore()
const dataPoolStore = useDataPoolStore()

// 获取选中的组件
const selectedComponent = computed(() => pageStore.selectedComponent)

// 当前激活的面板标签
const activeTab = ref('props')

// 获取所有数据项
const dataItems = computed(() => dataPoolStore.getAllDataItems)

// 样式属性
const styleProps = ref({
  width: '',
  height: '',
  top: '',
  left: '',
  backgroundColor: ''
})

// 组件属性
const componentProps = ref<Record<string, any>>({})

// 事件处理
const events = ref<Record<string, string>>({})

// 数据绑定相关
const bindingProp = ref('')
const bindingDataId = ref('')
const componentBindings = ref<Array<{propName: string, dataId: string}>>([])

// JSON编辑
const componentJson = computed(() => {
  if (!selectedComponent.value) return ''
  return JSON.stringify(selectedComponent.value, null, 2)
})

const showJsonEditor = ref(false)
const editingJson = ref('')
const jsonError = ref('')

// 监听选中组件变化，更新表单数据
watch(selectedComponent, (newComponent) => {
  if (newComponent) {
    // 更新样式属性
    styleProps.value.width = newComponent.style.width as string || 'auto'
    styleProps.value.height = newComponent.style.height as string || 'auto'
    styleProps.value.top = newComponent.style.top as string || '0px'
    styleProps.value.left = newComponent.style.left as string || '0px'
    styleProps.value.backgroundColor = newComponent.style.backgroundColor as string || ''
    
    // 更新组件属性
    componentProps.value = { ...newComponent.props }
    
    // 更新事件处理
    events.value = { ...newComponent.events || {} }
    
    // 更新数据绑定
    componentBindings.value = [...(newComponent.dataBindings || [])]
  }
}, { immediate: true })

// 更新样式
const updateStyle = (key: string, value: any) => {
  if (!selectedComponent.value) return
  
  const updates = {
    style: { [key]: value }
  }
  
  pageStore.updateComponent(selectedComponent.value.id, updates)
}

// 更新属性
const updateProps = (key: string, value: any) => {
  if (!selectedComponent.value) return
  
  const updates = {
    props: { [key]: value }
  }
  
  pageStore.updateComponent(selectedComponent.value.id, updates)
}

// 更新事件
const updateEvent = (eventName: string, code: string) => {
  if (!selectedComponent.value) return
  
  const updates = {
    events: { [eventName]: code }
  }
  
  pageStore.updateComponent(selectedComponent.value.id, updates)
}

// 复制JSON到剪贴板
const copyJson = () => {
  navigator.clipboard.writeText(componentJson.value)
    .then(() => alert('JSON已复制到剪贴板'))
    .catch(err => console.error('复制失败:', err))
}

// 打开JSON编辑器
watch(showJsonEditor, (show) => {
  if (show) {
    editingJson.value = componentJson.value
    jsonError.value = ''
  }
})

// 应用JSON修改
const applyJsonChanges = () => {
  try {
    const updatedComponent = JSON.parse(editingJson.value) as ComponentItem
    
    // 验证必要字段
    if (!updatedComponent.id || !updatedComponent.type) {
      throw new Error('组件必须包含id和type字段')
    }
    
    // 更新组件
    pageStore.updateComponent(updatedComponent.id, updatedComponent)
    
    // 关闭编辑器
    showJsonEditor.value = false
    jsonError.value = ''
  } catch (error) {
    jsonError.value = `JSON解析错误: ${(error as Error).message}`
  }
}

// 绑定数据
const bindData = () => {
  if (!bindingProp.value || !bindingDataId.value) return
  
  // 检查是否已存在相同的绑定
  const existingIndex = componentBindings.value.findIndex(b => b.propName === bindingProp.value)
  
  if (existingIndex >= 0) {
    // 更新已存在的绑定
    componentBindings.value[existingIndex].dataId = bindingDataId.value
  } else {
    // 添加新绑定
    componentBindings.value.push({
      propName: bindingProp.value,
      dataId: bindingDataId.value
    })
  }
  
  // 应用绑定
  applyDataBinding()
  
  // 重置选择
  bindingProp.value = ''
  bindingDataId.value = ''
}

// 移除绑定
const removeBinding = (index: number) => {
  componentBindings.value.splice(index, 1)
  applyDataBinding()
}

// 应用数据绑定
const applyDataBinding = () => {
  if (!selectedComponent.value) return
  
  // 为组件添加数据绑定信息
  const updates: any = {
    dataBindings: [...componentBindings.value]
  }
  
  // 更新组件
  pageStore.updateComponent(selectedComponent.value.id, updates)
}

// 获取数据项名称
const getDataItemName = (id: string): string => {
  const item = dataPoolStore.getDataItemById(id)
  return item ? item.name : '未知数据项'
}
</script>

<style lang="scss" scoped>
.property-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .panel-header {
    padding: 12px 16px;
    border-bottom: 1px solid #e0e0e0;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
    
    .panel-tabs {
      display: flex;
      margin-top: 10px;
      border-bottom: 1px solid #e0e0e0;
      
      .tab-item {
        padding: 6px 12px;
        cursor: pointer;
        font-size: 14px;
        color: #606266;
        border-bottom: 2px solid transparent;
        
        &.active {
          color: #409eff;
          border-bottom-color: #409eff;
        }
        
        &:hover {
          color: #409eff;
        }
      }
    }
  }
  
  .panel-content {
    flex: 1;
    overflow-y: auto;
    
    .empty-tip {
      text-align: center;
      color: #999;
      padding: 40px 0;
    }
    
    .property-section {
      margin-bottom: 24px;
      
      .section-title {
        font-size: 15px;
        font-weight: 500;
        margin: 0 0 12px 0;
        padding-bottom: 8px;
        border-bottom: 1px solid #eee;
      }
    }
    
    .property-item {
      margin-bottom: 16px;
      
      .property-label {
        font-size: 13px;
        color: #666;
        margin-bottom: 6px;
      }
      
      .property-value {
        font-size: 13px;
        color: #333;
        padding: 4px 0;
      }
      
      .color-input {
        height: 32px;
        padding: 0;
        width: 100%;
      }
      
      .code-editor, .json-viewer, .json-editor {
        font-family: monospace;
        font-size: 12px;
      }
    }
    
    .property-actions {
      display: flex;
      gap: 8px;
      margin-top: 8px;
    }
  }
  
  .json-editor-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    
    .modal-content {
      width: 80%;
      max-width: 600px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
      
      .modal-header {
        padding: 12px 16px;
        border-bottom: 1px solid #e0e0e0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        h4 {
          margin: 0;
          font-size: 16px;
        }
        
        .close-btn {
          background: none;
          border: none;
          font-size: 20px;
          cursor: pointer;
          color: #999;
          
          &:hover {
            color: #333;
          }
        }
      }
      
      .modal-body {
        padding: 16px;
        
        .error-message {
          color: #f56c6c;
          margin-top: 8px;
          font-size: 13px;
        }
      }
      
      .modal-footer {
        padding: 12px 16px;
        border-top: 1px solid #e0e0e0;
        display: flex;
        justify-content: flex-end;
        gap: 8px;
      }
    }
  }
}

</style>